package com.juli.v2xdemo.tcp.protocol.bean;

import android.util.Log;

import com.cz.basetool.CodeTool;
import com.cz.basetool.ui_work.util.log.AndroidConsoleLogPrinter;
import com.util.PcMacUtil;


public class CMD_55AA {
	private static final String TAG = "CMD_55AA";

	/*
	 * STX 帧开始标志，2字节，取值为55AAH,字符串方式： RSCTL
	 * 帧序列号，1字节：（1）帧序列号的低半字节为0-7，高半字节保留；（2）帧序列号每次加一，用于标识每一次的通信 LEN DATA域的长度，2字节
	 * CMD 命令头，1字节 DATA 发送的数据： BCC 异或校验值，从RSCTL到DATA所有字节的异或值，1字节
	 */

	public static final String STX = "55AA";
	private String LEN = "0000";
	private String RSCTL = "00";
	private String CMD = "00";
	private String DATA = "";
	private String CRC = "00";
	private String CMDSTR = "";

	private static int rsctl = 0;

	private CMD_55AA() {}

	/**
	 * 整合报文
	 * @param CMD
	 * @param DATA
	 * @return
	 */
	public static CMD_55AA create(String CMD, String DATA) {
		if (CMD == null || CMD.length() != 2 || DATA == null
				|| DATA.length() % 2 == 1)
			return null;
		CMD_55AA cmd = new CMD_55AA();
		cmd.RSCTL = "8" + rsctl;

		cmd.CMD = CMD.toUpperCase();
		cmd.DATA = DATA.toUpperCase();

		cmd.LEN =  CodeTool.num2HexStr((cmd.CMD + cmd.DATA).length() /2 + 1 ,2);
		cmd.CRC = PcMacUtil.calCRC16(cmd.RSCTL + cmd.CMD + cmd.DATA);
		Log.d(TAG, "create:CRC = " + cmd.CRC );

		cmd.CMDSTR = STX + cmd.LEN + cmd.RSCTL +  cmd.CMD + cmd.DATA + cmd.CRC;

		if (rsctl >= 7) {
			rsctl = 0;
		} else {
			rsctl++;
		}
		return cmd;
	}

	/**
	 * 拆卸报文
	 *
	 * @param CMDSTR
	 */

	public static CMD_55AA disassemble(String CMDSTR) {

		if (CMDSTR == null || CMDSTR.length() < 14 || CMDSTR.length() % 2 == 1)
			return null;
		CMDSTR = CMDSTR.toUpperCase();
		CMD_55AA cmd = new CMD_55AA();
		if (CMDSTR.substring(0, 4).equals(STX)) {
			cmd.LEN = CMDSTR.substring(4, 8);
			cmd.RSCTL = CMDSTR.substring(8, 10);
			cmd.CMD = CMDSTR.substring(10, 12);
			cmd.DATA = CMDSTR.substring(12, CMDSTR.length() - 4);
			cmd.CRC = CMDSTR.substring(CMDSTR.length() - 4, CMDSTR.length());
			cmd.CMDSTR = CMDSTR;

			if ((cmd.RSCTL + cmd.CMD + cmd.DATA + cmd.CRC ).length() / 2 == Integer.parseInt(cmd.LEN, 16)) {
				String calCrcResult = PcMacUtil.calCRC16(cmd.RSCTL + cmd.CMD + cmd.DATA);

 				if (calCrcResult.equalsIgnoreCase(cmd.CRC)) {
					return cmd;
				} else {
					AndroidConsoleLogPrinter.e(TAG, "bcc error" + "calCrcResult = " + calCrcResult + ",cmd.CRC = " + cmd.CRC );
					return null;
				}
			} else {
				AndroidConsoleLogPrinter.e(TAG, "lenth error");
				return null;
			}
		}
		return null;
	}

	/**
	 * 整条报文
	 *
	 * @return
	 */
	public String getCMDSTR() {
		return CMDSTR;
	}

	/**
	 * 帧序列号
	 *
	 * @return
	 */
	public String getRSCTL() {
		return RSCTL;
	}

	/**
	 * 内容长度
	 *
	 * @return
	 */
	public String getLEN() {
		return LEN;
	}

	/**
	 * 指令集
	 *
	 * @return
	 */
	public String getCMD() {
		return CMD;
	}

	/**
	 * 内容
	 *
	 * @return
	 */
	public String getDATA() {
		return DATA;
	}

	public String getCRC() {
		return CRC;
	}


}
